﻿namespace com.game
{
    using com.game.basic;
    using com.game.consts;
    using com.game.Helper;
    using com.game.i18n;
    using com.game.manager;
    using com.game.module;
    using com.game.module.core;
    using com.game.module.Dungeon;
    using com.game.module.effect;
    using com.game.module.hud;
    using com.game.module.map;
    using com.game.module.SystemData;
    using com.game.module.WiFiPvP;
    using com.game.Public.Confirm;
    using com.game.Public.Message;
    using com.game.SDK;
    using com.game.sound;
    using com.game.start;
    using com.game.utils;
    using com.liyong;
    using com.net;
    using com.net.interfaces;
    using com.net.p8583;
    using com.net.wifi_pvp;
    using com.u3d.bases.debug;
    using com.u3d.bases.joystick;
    using com.u3d.bases.loader;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using UnityEngine;

    public class Main : MonoBehaviour
    {
        [CompilerGenerated]
        private static Dictionary<string, int> <>f__switch$map4;
        [CompilerGenerated]
        private static Dictionary<string, int> <>f__switch$map5;
        private bool assetInit;
        private bool connected;
        private float connectTime;
        public GUISkin DebugSkin;
        private const int frameGap = 1;
        private const int grameCMDNum = 30;
        private readonly Dictionary<string, NetMsgCallback> handlerList = new Dictionary<string, NetMsgCallback>();
        public bool HideDebugButtons;
        public bool HidePrivate;
        private bool isInit;
        public bool loadServerBinDataXml;
        public static Main mainObj;
        private readonly IList<INetData> netDataList = new List<INetData>();
        private const int targetFrame = 30;
        public bool TestAI;
        public bool TestAttribute;
        public bool TestNet;
        public bool TestNetCommand;
        public bool TestNormalSoldier;
        public int TestSceneId;
        public bool TestSoul;

        public void addCMD(string cmd, NetMsgCallback callback)
        {
            if ((callback != null) && !StringUtils.isEmpty(cmd))
            {
                this.handlerList[cmd] = callback;
            }
        }

        private void AfterUpdate()
        {
            AssetManager.Instance.init(new LoadAssetFinish<UnityEngine.Object>(this.startLoadingFinish));
            EffectActionManager.Instance.InitDic();
        }

        public void App_Start()
        {
            Application.targetFrameRate = 30;
            Application.runInBackground = false;
            this.SetLogLevel();
            com.u3d.bases.debug.Log.info(this, "-Start() 1、bitLen:" + AppNet.bitLen);
            com.u3d.bases.debug.Log.info(this, "-Start() 2、language:" + ResMgr.instance.versionMgr.language + ", basePath:" + ResMgr.instance.versionMgr.basePath);
            com.u3d.bases.debug.Log.info(this, "-Start() 3、初始化配置【OK】");
            GameObject prefab = null;
            if (!ClientUpdate.updateInit)
            {
                UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
                prefab = (GameObject) ResMgr.instance.load("zh_CN/prefab/ui/UIRoot", null);
                prefab = Tools.addChild(base.gameObject, prefab, -30f);
                UnityEngine.Object.DestroyImmediate(Tools.find(base.gameObject, "uiroot(Clone)/viewtree/Logo"));
            }
            com.game.module.ViewTree.go = Tools.find(base.gameObject, "uiroot(Clone)/viewtree");
            com.game.module.Viewport.go = Tools.find(base.gameObject, "uiroot(Clone)/viewport");
            com.game.module.ViewTree.SetSubObj();
            MyHudText.hudview = Util.FindChildRecursive(com.game.module.ViewTree.go.transform, "hudview").gameObject;
            MyHudText.gameCamera = Tools.find(base.gameObject, "main_camera").camera;
            MyHudText.uiCamera = Util.FindChildRecursive(prefab.transform, "viewtree camera").camera;
            GameObject gameObject = Util.FindChildRecursive(com.game.module.ViewTree.go.transform, "hudview").gameObject;
            MyHealthBar.hudView = gameObject;
            PlayerBox.uiRoot = gameObject;
            HudView view = Tools.find(base.gameObject, "uiroot(Clone)/viewtree/hudview").AddComponent<HudView>();
            view.MountPoint = Tools.find(base.gameObject, "uiroot(Clone)/viewtree/hudview/mountpoint");
            HUDTextII.Parent = view.MountPoint;
            if (this.NeedUpdated && !ClientUpdate.updateFinish)
            {
                base.StartCoroutine(ClientUpdate.ClientStart(base.gameObject, new UpdateFinish(this.AfterUpdate), true));
            }
            else
            {
                this.AfterUpdate();
            }
            if (AppStart.MainAssembly == null)
            {
                AppStart.MainAssembly = Assembly.GetExecutingAssembly();
            }
            PhoneUtil.DonotSleep();
            base.gameObject.AddComponent<com.game.Public.InitManager.InitManager>();
            Physics.IgnoreLayerCollision(LayerMask.NameToLayer("Player"), LayerMask.NameToLayer("Player"));
        }

        private void AutoUpdateEnd()
        {
            SDKManager.SDKActivityBeforeLoginLog();
            SDKManager.SDKLogin();
        }

        private void Awake()
        {
            QualitySettings.masterTextureLimit = (SystemInfo.systemMemorySize > 0x400) ? 0 : 1;
            mainObj = this;
            base.gameObject.AddMissingComponent<NetDebug>();
        }

        private void BeforeQuitGameCallBack(string msg)
        {
            Application.Quit();
        }

        public void CancelForceUpdate(string msg)
        {
            Singleton<WaitingView>.Instance.CloseView();
            com.u3d.bases.debug.Log.info(this, "用户取消强制更新,退出游戏");
            this.QuitGame();
        }

        public void CancelNormalUpdate(string msg)
        {
            Singleton<WaitingView>.Instance.CloseView();
            com.u3d.bases.debug.Log.info(this, "用户取消普通更新");
            this.AutoUpdateEnd();
        }

        public void checkQuitClick()
        {
            if ((Application.platform == RuntimePlatform.Android) && Input.GetKeyDown(KeyCode.Escape))
            {
                if (AppStart.RunMode == 2)
                {
                    SDKManager.SDKBeforeQuitGame();
                }
                else
                {
                    ConfirmMgr.Instance.ShowSelectOneAlert(LanguageManager.GetWord("QuitAlertView.Message"), "SELECT_ONE", new ClickCallback(this.QuitClick), LanguageManager.GetWord("QuitAlertView.Quit"), null, LanguageManager.GetWord("QuitAlertView.Continue"));
                }
            }
        }

        public void CheckVersionFailure(string msg)
        {
            Singleton<WaitingView>.Instance.CloseView();
            com.u3d.bases.debug.Log.info(this, "新版本检测失败");
            MessageManager.Show("版本检测失败");
            this.AutoUpdateEnd();
        }

        private void Close91PauseTips(string msg)
        {
        }

        private void doHandler()
        {
            if (this.netDataList.Count >= 1)
            {
                for (int i = 30; (i > 0) && (this.netDataList.Count > 0); i--)
                {
                    INetData item = this.netDataList[0];
                    this.netDataList.Remove(item);
                    string cMD = item.GetCMD();
                    NetDebug.AddConsole(cMD);
                    if (this.handlerList.ContainsKey(cMD))
                    {
                        this.handlerList[cMD](item);
                    }
                    else
                    {
                        com.u3d.bases.debug.Log.info(this, "-doHandler() 未注册CMD:" + item.GetCMD());
                    }
                }
            }
        }

        public void GetAnnounce(string url)
        {
            base.StartCoroutine(this.RequestServerInfo(url));
        }

        private void initApp()
        {
            com.u3d.bases.debug.Log.info(this, "-initApp() 6、开始初始化模块应用！");
            if (!this.isInit)
            {
                this.isInit = true;
                AppNet.main = this;
                AppFacde.instance.Init();
                com.u3d.bases.debug.Log.info(this, "-initApp() 7、系统模块初始化【OK】");
                Singleton<LoginControl>.Instance.maxdelay = 10;
                Singleton<LoginControl>.Instance.heartGap = 5;
                Singleton<AtlasManager>.Instance.Init();
                CommonModelAssetManager.Instance.Init();
                base.gameObject.AddComponent<ShapeMgr>();
                Singleton<ComboHitView>.Instance.OpenView();
                com.u3d.bases.debug.Log.info(this, "-initApp() 8、登陆UI打开【OK】");
                DevelopHelper.Init();
            }
        }

        private void Login()
        {
            Singleton<LoginControl>.Instance.SendHeartMsgDirect();
            Singleton<LoginMode>.Instance.SendClientInfo();
            Singleton<WaitingView>.Instance.CloseView();
            Singleton<LoginMode>.Instance.getRoleList();
            SDKManager.SDKLoginServerLog(Singleton<LoginMode>.Instance.serverId.ToString());
            Time.timeScale = 1f;
        }

        private void Login91Cancel(string msg)
        {
            if (!Singleton<LoginMode>.Instance.IsOpenLoginView)
            {
                SDKManager.SDK91GuestLogin();
            }
        }

        private void Login91Fail(string msg)
        {
            ConfirmMgr.Instance.ShowOkAlert("登陆发生错误：" + msg, "OK_CANCEL", new ClickCallback(this.QuitGame), LanguageManager.GetWord("ConfirmView.Ok"));
        }

        private void Login91GuestCancel(string msg)
        {
            if (!Singleton<LoginMode>.Instance.IsOpenLoginView)
            {
                this.QuitGame();
            }
        }

        private void Login91GuestFail(string msg)
        {
            ConfirmMgr.Instance.ShowOkAlert("登陆发生错误：" + msg, "OK_CANCEL", new ClickCallback(this.QuitGame), LanguageManager.GetWord("ConfirmView.Ok"));
        }

        private void Login91GuestSuccess(string msg)
        {
            char[] separator = new char[] { ',' };
            string[] strArray = msg.Split(separator);
            Singleton<LoginMode>.Instance.UpdateLoginInfo(strArray[0], strArray[1], strArray[1], "0", string.Empty, string.Empty);
            this.PlatformLoginFinish();
        }

        private void Login91Success(string msg)
        {
            char[] separator = new char[] { ',' };
            string[] strArray = msg.Split(separator);
            Singleton<LoginMode>.Instance.UpdateLoginInfo(strArray[0], strArray[1], strArray[2], "0", string.Empty, string.Empty);
            this.PlatformLoginFinish();
        }

        public void LoginCancel(string msg)
        {
            if (!Singleton<LoginMode>.Instance.IsOpenLoginView)
            {
                this.QuitGame();
            }
        }

        public void LoginComplete(string msg)
        {
            char[] separator = new char[] { ',' };
            string[] strArray = msg.Split(separator);
            Singleton<LoginMode>.Instance.UpdateLoginInfo(strArray[3], strArray[5], strArray[0], strArray[1], strArray[2], strArray[4]);
            this.PlatformLoginFinish();
        }

        public void LoginError(string errmsg)
        {
            ConfirmMgr.Instance.ShowOkAlert("登陆错误：" + errmsg, "OK_CANCEL", new ClickCallback(this.QuitGame), LanguageManager.GetWord("ConfirmView.Ok"));
        }

        public void LoginException(string msg)
        {
            ConfirmMgr.Instance.ShowOkAlert("登陆发生异常：" + msg, "OK_CANCEL", new ClickCallback(this.QuitGame), LanguageManager.GetWord("ConfirmView.Ok"));
        }

        private void LoginStateCallback_91(string msg)
        {
            string key = msg;
            if (key != null)
            {
                int num;
                if (<>f__switch$map5 == null)
                {
                    Dictionary<string, int> dictionary = new Dictionary<string, int>(3);
                    dictionary.Add("accountLogin", 0);
                    dictionary.Add("guestLogin", 1);
                    dictionary.Add("notLogin", 2);
                    <>f__switch$map5 = dictionary;
                }
                if (<>f__switch$map5.TryGetValue(key, out num))
                {
                }
            }
        }

        public void NetWorkError(string msg)
        {
            Singleton<WaitingView>.Instance.CloseView();
            com.u3d.bases.debug.Log.info(this, "网络链接错误");
            ConfirmMgr.Instance.ShowOkAlert("网络链接错误", "OK_CANCEL", new ClickCallback(this.QuitGame), LanguageManager.GetWord("ConfirmView.Ok"));
        }

        public void NotNewVersion(string msg)
        {
            Singleton<WaitingView>.Instance.CloseView();
            com.u3d.bases.debug.Log.info(this, "已经是最新版本");
            this.AutoUpdateEnd();
        }

        public void NotSDCard(string msg)
        {
            Singleton<WaitingView>.Instance.CloseView();
            com.u3d.bases.debug.Log.info(this, "没有SD卡");
            ConfirmMgr.Instance.ShowOkAlert("没有SD卡", "OK_CANCEL", new ClickCallback(this.QuitGame), LanguageManager.GetWord("ConfirmView.Ok"));
        }

        public void OnApplicationPause(bool pauseStatus)
        {
            if (this.isInit)
            {
                com.u3d.bases.debug.Log.info(this, "Application Pause:==========================" + pauseStatus);
                if (pauseStatus)
                {
                    SDKManager.SDKPauseGame();
                }
            }
        }

        public void OnApplicationQuit()
        {
            LogHelper.Release();
            WifiLAN.Destroy();
        }

        private void OnDestroy()
        {
            if (AppNet.gameNet != null)
            {
                AppNet.gameNet.close();
                com.u3d.bases.debug.Log.info(this, "-OnDestroy() Socket销毁成功！");
            }
        }

        private void OpenLoginView()
        {
            Singleton<LoginPanel>.Instance.OpenView();
        }

        private void Pay91Cancel(string msg)
        {
        }

        private void Pay91Fail(string msg)
        {
            MessageManager.Show("支付失败：" + msg);
        }

        private void Pay91Success(string msg)
        {
            MessageManager.Show("支付成功：" + msg);
        }

        private void PlatformLoginFinish()
        {
            AppNet.gameNet = NetFactory.newSocket();
            AppNet.gameNet.statusListener(new NetStatusCallback(this.receiveNetStatus));
            this.OpenLoginView();
            HudView.Instance.StartLoadAsset();
            Singleton<EffectCameraMgr>.Instance.Init();
            Singleton<StoryMode>.Instance.Init();
            EffectMgr.Instance.PreloadMainEffect("20008");
            this.assetInit = true;
        }

        private void PreloadStartMovieResource()
        {
            SoundMgr.Instance.PreloadSceneAudio("1017");
        }

        public void QuitClick()
        {
            com.u3d.bases.debug.Log.info(this, "退出应用");
            this.QuitGame();
        }

        public void QuitGame()
        {
            com.u3d.bases.debug.Log.info(this, "Application quit called");
            Application.Quit();
        }

        public void receiveNetMsg(INetData receiveData)
        {
            string cMD = receiveData.GetCMD();
            com.u3d.bases.debug.Log.info(this, string.Concat(new object[] { "Received Data CMD :", cMD, "  ServerTimestamp:", ServerTime.Instance.Timestamp }));
            if (cMD == "256")
            {
                this.handlerList[cMD](receiveData);
            }
            else
            {
                IList<INetData> netDataList = this.netDataList;
                lock (netDataList)
                {
                    this.netDataList.Add(receiveData);
                }
            }
        }

        public void receiveNetStatus(string status)
        {
            string key = status;
            if (key != null)
            {
                int num;
                if (<>f__switch$map4 == null)
                {
                    Dictionary<string, int> dictionary = new Dictionary<string, int>(3);
                    dictionary.Add("linkOk", 0);
                    dictionary.Add("linkFail", 1);
                    dictionary.Add("linking", 2);
                    <>f__switch$map4 = dictionary;
                }
                if (<>f__switch$map4.TryGetValue(key, out num))
                {
                    switch (num)
                    {
                        case 0:
                            com.u3d.bases.debug.Log.info(this, string.Concat(new object[] { "-receiveNetStatus() linkOk 连接服务器[", AppNet.ip, ":", AppNet.port, "][", I18n.instance.getSocketTip("A0", 1), "]" }));
                            this.connected = true;
                            this.Login();
                            break;

                        case 1:
                            com.u3d.bases.debug.Log.info(this, string.Concat(new object[] { "-receiveNetStatus() linkFail 连接服务器[", AppNet.ip, ":", AppNet.port, "][", I18n.instance.getSocketTip("A0", 2), "]" }));
                            this.connected = false;
                            Singleton<NetworkInfoView>.Instance.SetDisConnect();
                            Singleton<StoryMode>.Instance.DataUpdate(Singleton<StoryMode>.Instance.FORCE_STOP_STORY);
                            if (Application.platform != RuntimePlatform.Android)
                            {
                                ConfirmMgr.Instance.ShowOkAlert(LanguageManager.GetWord("ConnetAlertView.Message"), "CONNECT_SERVER_ERROR", new ClickCallback(this.ReConnectClick), LanguageManager.GetWord("ConnetAlertView.Reconnect"));
                            }
                            else
                            {
                                ConfirmMgr.Instance.ShowSelectOneAlert(LanguageManager.GetWord("ConnetAlertView.Message"), "CONNECT_SERVER_ERROR", new ClickCallback(this.ReConnectClick), LanguageManager.GetWord("ConnetAlertView.Reconnect"), new ClickCallback(this.QuitClick), LanguageManager.GetWord("ConnetAlertView.Quit"));
                            }
                            Time.timeScale = 0f;
                            Singleton<WaitingView>.Instance.CloseView();
                            return;

                        case 2:
                            com.u3d.bases.debug.Log.info(this, string.Concat(new object[] { "-receiveNetStatus() linking 连接服务器[", AppNet.ip, ":", AppNet.port, "][", I18n.instance.getSocketTip("A0", 3), "]" }));
                            this.connected = false;
                            Singleton<WaitingView>.Instance.OpenView();
                            break;
                    }
                }
            }
        }

        public void ReConnectClick()
        {
            com.u3d.bases.debug.Log.info(this, "开始重连");
            this.netDataList.Clear();
            base.StopAllCoroutines();
            Singleton<LoginControl>.Instance.ResetHeartBeatState();
            AppNet.gameNet.connect(AppNet.gameNet.ip, AppNet.gameNet.port);
        }

        private static bool ReliableCheck()
        {
            return Application.genuineCheckAvailable;
        }

        public void removeCMD(string cmd)
        {
            if (!StringUtils.isEmpty(cmd))
            {
                this.handlerList.Remove(cmd);
            }
        }

        [DebuggerHidden]
        private IEnumerator RequestServerInfo(string url)
        {
            return new <RequestServerInfo>c__Iterator15 { url = url, <$>url = url };
        }

        private void SDK91InitSucceed(string msg)
        {
            if (msg == "normal")
            {
                SDKManager.SDKActivityOpenLog();
                this.App_Start();
            }
            else if (msg == "force_close")
            {
                this.QuitGame();
            }
        }

        private void SetLogLevel()
        {
            LogHelper.Init(AppStart.RunMode);
            com.u3d.bases.debug.Log.addLevel("5");
            NetParams.addLevel("5");
            com.u3d.bases.debug.Log.ClearLog();
        }

        public void SsjjsyException(string msg)
        {
            Singleton<WaitingView>.Instance.CloseView();
            com.u3d.bases.debug.Log.info(this, "其它异常");
            ConfirmMgr.Instance.ShowOkAlert("更新发生异常", "OK_CANCEL", new ClickCallback(this.QuitGame), LanguageManager.GetWord("ConfirmView.Ok"));
        }

        private void Start()
        {
            GameConfig.readBinDataFromServer = this.loadServerBinDataXml;
            Time.timeScale = 1f;
            AppNet.main = this;
            if (AppStart.RunMode == 0)
            {
                this.App_Start();
            }
            else if (AppStart.RunMode == 1)
            {
                SDKManager.SDKInit();
                SDKManager.SDKActivityOpenLog();
                this.App_Start();
            }
            else if (AppStart.RunMode == 2)
            {
                SDKManager.SDKInit();
            }
        }

        private void startLoadingFinish(UnityEngine.Object obj)
        {
            UpdateView.Instance.closeView();
            Singleton<StartLoadingView>.Instance.CloseView();
            if (AppStart.RunMode == 0)
            {
                this.PlatformLoginFinish();
            }
            else if (AppStart.RunMode == 1)
            {
                Singleton<WaitingView>.Instance.OpenView();
                SDKManager.SDKAutoUpdate();
            }
            else if (AppStart.RunMode == 2)
            {
                this.AutoUpdateEnd();
            }
        }

        private void Update()
        {
            if (this.connected && !this.isInit)
            {
                this.connectTime = Time.time;
                this.initApp();
            }
            else
            {
                if (AppNet.gameNet != null)
                {
                    AppNet.gameNet.Update();
                }
                if (this.connected)
                {
                    if ((Time.frameCount % 30) == 0)
                    {
                        if (Singleton<LoginControl>.Instance.CheckTimeOut())
                        {
                            com.u3d.bases.debug.Log.info(this, "检测到心跳网络超时");
                            if (AppNet.gameNet != null)
                            {
                                AppNet.gameNet.close();
                            }
                            Singleton<NetworkInfoView>.Instance.SetDisConnect();
                        }
                        else
                        {
                            Singleton<LoginControl>.Instance.SendHeartMsg();
                        }
                    }
                    this.doHandler();
                }
                if ((Time.frameCount % 1) == 0)
                {
                    JoystickController.instance.Update();
                    SelfPlayerManager.instance.Update();
                    PlayerMgr.instance.execute();
                    Singleton<MonsterActivator>.Instance.Update();
                    Singleton<MonsterMgr>.Instance.execute();
                    Singleton<ChestMgr>.Instance.Execute();
                    ViewManager.Update();
                    DungeonMgr.Instance.Update();
                    PrivateMgr.Instance.Update();
                    BattleObjectMgr.Instance.Update();
                    WifiLAN.Instance.Update();
                    WifiPvpManager.Instance.Update();
                }
                GlobalAPI.tickManager.Update();
            }
            if (this.assetInit)
            {
                this.checkQuitClick();
            }
        }

        public bool NeedUpdated
        {
            get
            {
                return (Application.platform == RuntimePlatform.IPhonePlayer);
            }
        }

        [CompilerGenerated]
        private sealed class <RequestServerInfo>c__Iterator15 : IEnumerator, IDisposable, IEnumerator<object>
        {
            internal object $current;
            internal int $PC;
            internal string <$>url;
            internal WWW <request>__0;
            internal string <txt>__1;
            internal string url;

            [DebuggerHidden]
            public void Dispose()
            {
                this.$PC = -1;
            }

            public bool MoveNext()
            {
                uint num = (uint) this.$PC;
                this.$PC = -1;
                switch (num)
                {
                    case 0:
                        this.<request>__0 = new WWW(this.url);
                        this.$current = this.<request>__0;
                        this.$PC = 1;
                        return true;

                    case 1:
                        if (this.<request>__0.error == null)
                        {
                            this.<txt>__1 = this.<request>__0.text;
                            Singleton<UpdateAnnounceMode>.Instance.SaveAnnounce(this.<txt>__1);
                            this.<request>__0.Dispose();
                        }
                        this.$PC = -1;
                        break;
                }
                return false;
            }

            [DebuggerHidden]
            public void Reset()
            {
                throw new NotSupportedException();
            }

            object IEnumerator<object>.Current
            {
                [DebuggerHidden]
                get
                {
                    return this.$current;
                }
            }

            object IEnumerator.Current
            {
                [DebuggerHidden]
                get
                {
                    return this.$current;
                }
            }
        }
    }
}

